import { ref } from 'vue'
import io from 'socket.io-client'
import { ElMessage } from 'element-plus'

// 单例模式 - 全局共享
let socket = null
const isConnected = ref(false)

export function useSocket() {
  // 连接WebSocket
  const connect = (token) => {
    if (socket && socket.connected) {
      console.log('WebSocket 已存在连接')
      return socket
    }

    console.log('正在连接 WebSocket...')
    socket = io('http://localhost:7001', {
      query: {
        token
      },
      transports: ['websocket', 'polling'],
      reconnection: true,
      reconnectionDelay: 1000,
      reconnectionAttempts: 5
    })

    socket.on('connect', () => {
      console.log('✅ WebSocket 已连接')
      isConnected.value = true
    })

    socket.on('disconnect', (reason) => {
      console.log('❌ WebSocket 已断开:', reason)
      isConnected.value = false
    })

    socket.on('connect_error', (error) => {
      console.error('❌ WebSocket 连接错误:', error)
      isConnected.value = false
      ElMessage.error('WebSocket连接失败')
    })

    socket.on('error', (data) => {
      console.error('WebSocket 错误:', data)
      ElMessage.error(data.msg || 'WebSocket错误')
    })

    return socket
  }

  // 断开连接
  const disconnect = () => {
    if (socket) {
      socket.disconnect()
      socket = null
      isConnected.value = false
    }
  }

  // 发送消息
  const sendMessage = (messageData) => {
    return new Promise((resolve, reject) => {
      console.log('📤 准备发送消息:', messageData)
      console.log('🔌 Socket 状态:', {
        exists: !!socket,
        connected: socket?.connected,
        isConnected: isConnected.value
      })

      if (!socket) {
        console.error('❌ Socket 不存在')
        reject(new Error('WebSocket未初始化'))
        return
      }

      if (!socket.connected) {
        console.error('❌ Socket 未连接')
        reject(new Error('WebSocket未连接'))
        return
      }

      console.log('✅ 发送消息到服务器...')
      socket.emit('sendMessage', messageData)

      // 监听发送确认
      const timeout = setTimeout(() => {
        console.error('⏱️ 发送超时')
        reject(new Error('发送超时'))
      }, 5000)

      socket.once('messageSent', (response) => {
        clearTimeout(timeout)
        console.log('📨 收到服务器响应:', response)
        if (response.code === 0) {
          resolve(response.data)
        } else {
          reject(new Error(response.msg))
        }
      })
    })
  }

  // 监听新消息
  const onNewMessage = (callback) => {
    if (socket) {
      socket.on('newMessage', (response) => {
        if (response.code === 0) {
          callback(response.data)
        }
      })
    }
  }

  // 加入会话
  const joinConversation = (conversationId) => {
    if (socket && socket.connected) {
      socket.emit('joinConversation', { conversation_id: conversationId })
    }
  }

  // 离开会话
  const leaveConversation = (conversationId) => {
    if (socket && socket.connected) {
      socket.emit('leaveConversation', { conversation_id: conversationId })
    }
  }

  // 标记已读
  const markAsRead = (messageIds, senderId) => {
    if (socket && socket.connected) {
      socket.emit('markAsRead', { message_ids: messageIds, sender_id: senderId })
    }
  }

  // 发送正在输入状态
  const sendTyping = (receiverId, isTyping = true) => {
    if (socket && socket.connected) {
      socket.emit('typing', { receiver_id: receiverId, is_typing: isTyping })
    }
  }

  // 监听对方正在输入
  const onUserTyping = (callback) => {
    if (socket) {
      socket.on('userTyping', (response) => {
        if (response.code === 0) {
          callback(response.data)
        }
      })
    }
  }

  // 监听消息已读
  const onMessagesRead = (callback) => {
    if (socket) {
      socket.on('messagesRead', (response) => {
        if (response.code === 0) {
          callback(response.data)
        }
      })
    }
  }

  // 移除所有监听器
  const removeAllListeners = () => {
    if (socket) {
      socket.off('newMessage')
      socket.off('userTyping')
      socket.off('messagesRead')
      socket.off('messageSent')
    }
  }

  return {
    socket,
    isConnected,
    connect,
    disconnect,
    sendMessage,
    onNewMessage,
    joinConversation,
    leaveConversation,
    markAsRead,
    sendTyping,
    onUserTyping,
    onMessagesRead,
    removeAllListeners
  }
}

